// 登陆注册
var express = require('express')
var router = express.Router()
const { getALL, getOne, exec } = require('../../db')

// 登录
router.post('/login', async (req, res) => {
  const { username, password } = req.body
  let sql = `select * from user where username='${username}'`
  const data = await getALL(sql)
  if (!data[0]) {
    res.send({ code: 202, message: '登陆失败' })
  } else {
    if (data[0].password == password) {
      // 修改用户登录状态
      // UPDATE <表名> SET 字段 1=值 1 [,字段 2=值 2… ] [WHERE 子句 ]
      let sql2 = `update user set user_onlinestatus='true' where id=${data[0].id}`
      await exec(sql2)
      res.send({ code: 200, message: '登陆成功', data: data[0] })
    } else {
      res.send({ code: 202, message: '登录失败' })
    }
  }
})

// 退出登录,修改用户登陆状态user_onlinestatus
router.post('/logout', async (req, res) => {
  const { username } = req.body
  let sql = `update user set user_onlinestatus='false' where username='${username}'`
  await exec(sql)
  res.send({
    code: 200,
    message: '退出登录!',
  })
})

// 注册
router.post('/signin', async (req, res) => {
  const { username, password } = req.body
  let sql = `insert into user(username,password) values('${username}','${password}')`
  const data = await exec(sql)
  res.send({
    code: 200,
    message: '注册成功!',
  })
})

// 检查用户名是否已被注册
router.post('/checkName', async (req, res) => {
  const { username } = req.body
  let sql = `select * from user where username='${username}'`
  const data = await exec(sql)
  if (data.length != 0) {
    res.send({
      code: 250,
      message: '该用户名已被注册!',
    })
  } else {
    res.send({
      code: 200,
      message: '可以注册!',
    })
  }
})

module.exports = router
